/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.example.client.web.controller;

import org.pajamas.starter.core.vo.ResultVo;
import org.pajamas.starter.integration.module.context.PajamasPropSrcConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author william
 * @since 2024/1/28
 */
@RequestMapping("/test-cloud")
@RestController
@RefreshScope
public class TestCloudController {
    @Value("${org.pajamas.example.key:none}")
    private String value;

    @Autowired
    DiscoveryClient client;
    @Value("${" + PajamasPropSrcConstants.INSTANCE_ID + "}")
    private String instanceId;

    @Autowired(required = false)
    private RestTemplate restTemplate;
    @Value("${spring.application.name}")
    private String applicationName;

    @RequestMapping("/refresh")
    public ResultVo refresh(String string) {
        return ResultVo.builder().payload(this.value).build();
    }

    @RequestMapping("/ribbon/{code}")
    public ResultVo ribbon(@PathVariable("code") String code) {
        String url = "http://angel-river/media-type/" + code;
        ResponseEntity<ResultVo> responseEntity = restTemplate.getForEntity(url, ResultVo.class);
        return responseEntity.getBody();
    }

    @RequestMapping("/serviceInstances")
    public ResultVo serviceInstances() {
        List<ServiceInstance> instances = this.client.getInstances(this.applicationName);
        return ResultVo.builder().payload(instances).build();
//        return ResultVo.builder().payload(this.instanceId).build();
    }
}
